<template>
<v-container class="play_window">
  <v-app-bar
    app
    color="#ffaf64"
    style="border-radius: 30px; "
    src="../../static/img/UI/redHeader.png"
  >
    <v-spacer></v-spacer>
    <span>{{ $store.state.Time }}</span>
    <v-spacer></v-spacer>
    <v-dialog
      transition="dialog-bottom-transition"
      max-width="600"
    >
      <template v-slot:activator="{on, attrs}">
        <v-btn
          elevation="2"
          v-bind="attrs"
          v-on="on"
          class="menu-button"
        >重新开始</v-btn>
      </template>
      <template v-slot:default="dialog">
        <v-card>
          <v-toolbar
            color="primary"
            dark
            src="../../static/img/UI/redHeader.png"
          >您确定要重新开始吗？</v-toolbar>
          <v-card-actions class="justify-end">
            <v-btn
              text
              @click="restart(); dialog.value = false"
            >是的</v-btn>
            <v-btn
              text
              @click="dialog.value = false"
            >关闭</v-btn>
          </v-card-actions>
        </v-card>
      </template>
    </v-dialog>
    <v-dialog
      transition="dialog-bottom-transition"
      max-width="600"
    >
      <template v-slot:activator="{on, attrs}">
        <v-btn
          elevation="2"
          v-bind="attrs"
          v-on="on"
          class="menu-button"
        >返回主页</v-btn>
      </template>
      <template v-slot:default="dialog">
        <v-card>
          <v-toolbar
            color="primary"
            dark
            src="../../static/img/UI/redHeader.png"
          >您确定要返回主页吗？</v-toolbar>
          <v-card-actions class="justify-end">
            <v-btn
              text
              @click="$router.push('/'); dialog.value = false"
            >是的</v-btn>
            <v-btn
              text
              @click="dialog.value = false"
            >关闭</v-btn>
          </v-card-actions>
        </v-card>
      </template>
    </v-dialog>
  </v-app-bar>

  <audio ref="selected_audio" :src="$store.state.PlayingMusic"></audio>
<!--  <audio ref="press_audio" :src="PressAudio.src"></audio>-->

  <v-container class="back-img">
    <div
      class="cloud score-cloud"
    ></div>
    <div
      class="sc-tip"
    >
      {{ tip }}
    </div>
    <div
      class="score perfect"
    >
      <span class="score-tip">完美 {{ score.perfect }}</span>
    </div>
    <div
      class="score good"
    >
      <span class="score-tip">良好 {{ score.good }}</span>
    </div>
    <div
      class="score miss"
    >
      <span class="score-tip">错过 {{ score.miss }}</span>
    </div>
  </v-container>

  <div
    class="board"
  >
    <div
      class="round action-point"
      v-show="leftRoundIsVisible"
      :style="{'margin-left': leftRoundPosition + '%'}"
    >
    </div>
    <v-container
      class="drum action-point"
      :style="{'margin-left': judgePosition + '%'}"
    >
      <v-container
        class="button-press"
        v-show="buttonPressed"
      ></v-container>
      <v-container
        class="judge-button"
      ></v-container>
    </v-container>
    <div
      class="round action-point"
      v-show="rightRoundIsVisible"
      :style="{'margin-left': rightRoundPosition + '%'}"
    >
    </div>
    <div
      class="cloud lcloud"
    ></div>
    <div
      class="cloud rcloud"
    ></div>
  </div>

<!--  <v-bottom-navigation-->
<!--    class="v-bottom-navigation&#45;&#45;fixed"-->
<!--    style="border-radius: 30px"-->
<!--  >-->
<!--    <v-spacer></v-spacer>-->
<!--    -->
<!--    <v-spacer></v-spacer>-->
<!--  </v-bottom-navigation>-->
</v-container>
</template>

<script>
export default {
  name: 'PlayingPage',
  data () {
    return {
      ButtonList: ['a', 's', 'd', 'f'],

      inAnimation: [],

      leftRoundPosition: -10,
      leftRoundIsVisible: false,
      rightRoundPosition: 100,
      rightRoundIsVisible: false,
      judgePosition: 45,

      leftShowTime: [2000, 4000, 4000, 4000, 4000, 4000],
      rightShowTime: [4000, 4000, 4000, 4000, 4000, 4000],

      // 判定
      buttonPressed: false,
      PositionWhenPressBlank: 100,
      gameState: 'waiting',
      leftTouch: false,
      rightTouch: false,
      perfectRange: 4,
      goodRange: 8,
      missRange: 12,

      // 成绩
      tip: '尚未开始',
      score: {
        perfect: 0,
        good: 0,
        miss: 0
      },

      Angle: 90
    }
  },
  mounted () {
    setInterval(this.changeTime, 1000)
    for (let i = 0; i < this.ButtonList.length; i++) {
      this.inAnimation.push(false)
    }
    window.addEventListener('keydown', (e) => {
      const key = e.key
      if (key === ' ') {
        this.buttonPressed = true
        if (this.gameState === 'waiting') {
          this.startGame()
        } else {
          if (this.gameState === 'start') {
            if (this.leftRoundPosition > this.judgePosition - this.missRange) {
              this.leftTouch = true
              if (this.leftRoundPosition > this.judgePosition - this.goodRange) {
                this.tip = '切合!'
                this.score.good += 1
              } else {
                if (this.leftRoundPosition > this.judgePosition - this.perfectRange) {
                  this.tip = '完美!'
                  this.score.perfect += 1
                } else {
                  this.tip = '离弦!'
                  this.score.miss += 1
                }
              }
            }
            if (this.rightRoundPosition < this.judgePosition + this.missRange) {
              this.rightTouch = true
              if (this.rightRoundPosition < this.judgePosition + this.goodRange) {
                this.tip = '切合!'
                this.score.good += 1
              } else {
                if (this.rightRoundPosition < this.judgePosition + this.missRange) {
                  this.tip = '完美!'
                  this.score.perfect += 1
                } else {
                  this.tip = '离弦!'
                  this.score.miss += 1
                }
              }
            }
          }
        }
      }
    })
    window.addEventListener('keyup', (e) => {
      const key = e.key
      if (key === ' ') {
        this.buttonPressed = false
      }
    })
  },
  methods: {
    changeTime: function () {
      const d = new Date()
      let weekday = ''
      switch (d.getDay()) {
        case 0:
          weekday = '星期一'
          break
        case 1:
          weekday = '星期二'
          break
        case 2:
          weekday = '星期三'
          break
        case 3:
          weekday = '星期四'
          break
        case 4:
          weekday = '星期五'
          break
        case 5:
          weekday = '星期六'
          break
        case 6:
          weekday = '星期日'
          break
      }
      let hour = d.getHours()
      if (hour < 10) hour = '0' + hour.toString()
      let minute = d.getMinutes()
      if (minute < 10) minute = '0' + minute.toString()
      let second = d.getSeconds()
      if (second < 10) second = '0' + second.toString()
      this.$store.state.Time = d.getFullYear().toString() + '/' +
        (d.getMonth() + 1).toString() + '/' +
        d.getDate().toString() + ' ' +
        weekday + ' ' +
        hour + ':' +
        minute.toString() + ':' +
        second.toString()
    },
    leftRoundMove: function () {
      if (this.leftRoundPosition < this.judgePosition) {
        this.leftRoundIsVisible = true
        this.leftRoundPosition += 1
        setTimeout(this.leftRoundMove, 40)
      } else {
        if (this.leftTouch === false) {
          this.tip = '离弦!'
          this.score.miss += 1
        } else {
          this.leftTouch = true
        }
        this.leftRoundIsVisible = false
        this.leftRoundPosition = -10
      }
    },
    rightRoundMove: function () {
      if (this.rightRoundPosition > this.judgePosition) {
        this.rightRoundIsVisible = true
        this.rightRoundPosition -= 1
        setTimeout(this.rightRoundMove, 40)
      } else {
        if (this.rightTouch === false) {
          this.tip = '离弦!'
          this.score.miss += 1
        } else {
          this.rightTouch = true
        }
        this.rightRoundIsVisible = false
        this.rightRoundPosition = 100
      }
    },
    leftShow: function (i) {
      if (this.gameState !== 'waiting') {
        if (i < this.$store.state.PlayingTimeList.length) {
          setTimeout(this.leftRoundMove, this.$store.state.PlayingTimeList[i])
          setTimeout(this.leftShow, this.$store.state.PlayingTimeList[i] + 100, i + 2)
        } else {
          // eslint-disable-next-line no-undef
          const app = tcb.init({ env: 'rhythm-8gijcn1i263ac8ec' })

          const auth = app.auth()

          auth.anonymousAuthProvider().signIn() // 匿名登录，实际业务时根据需要进行调整
            .then(() => {
              console.log('数据库用户登录成功') // 登录成功
            }).catch(err => {
              console.log('数据库用户登录失败', err) // 登录失败
            })

          const db = app.database()

          db.collection('score')
            .where({
              uname: this.$store.state.UserName
            })
            .update({
              one: (this.score.perfect * 8 + this.score.good * 4)
            })
          db.collection('log')
            .add({
              uid: this.$store.state.UserName,
              op: '歌曲成绩' + this.$store.state.PlayingMusicName + ' -score ' + (this.score.perfect * 8 + this.score.good * 4),
              time: Date.now()
            })
        }
      }
    },
    rightShow: function (i) {
      if (this.gameState !== 'waiting') {
        if (i < this.rightShowTime.length) {
          setTimeout(this.rightRoundMove, this.$store.state.PlayingTimeList[i])
          setTimeout(this.rightShow, this.$store.state.PlayingTimeList[i] + 100, i + 2)
        }
      }
    },
    sleep: function (time) {
      return new Promise((resolve) => setTimeout(resolve, time))
    },
    startGame: function () {
      this.gameState = 'start'
      this.$refs.selected_audio.play()
      this.leftShow(0)
      this.rightShow(1)
    },
    restart: function () {
      this.gameState = 'waiting'
      this.score.perfect = 0
      this.score.good = 0
      this.score.miss = 0
      this.tip = '尚未开始！'
      this.$router.go(0)
    }
  }
}
</script>

<style lang="scss" scoped>
.back-img {
  border-radius: 20px;
  height:200px;
  background: rgba(0, 0, 0, 0.1);
  background-size: 100% 100%;
}
.menu-button {
  height: 40px;
  width: 100px;
  margin-right: 20px;
  background-image: url("../../static/img/UI/Button.png");
  color: azure;
  font-family: '华文楷体', sans-serif;
}
.menu-button:hover {
  height: 45px;
  width: 112px;
}
.score-cloud {
  margin-top: 80px;
  background-image: url("../../static/img/UI/Cloud.png");
  background-size: 100% 100%;
  animation: fadeInLeft;
  animation-duration: 2s;
}
.sc-tip {
  position: fixed;
  margin-left: 35%;
  height: 100px;
  width: 40%;
  background: rgba(0, 0.2, 0.1, 0.1);
  text-align: center;
  font-family: "华文楷体", serif;
  font-size: 60px;
  color: black;
  animation: fadeInLeft;
  animation-duration: 2s;
}
.score {
  position: fixed;
  height: 70px;
  width: 130px;
  margin-top: 100px;
  background-image: url("../../static/img/UI/scoreboard.png");
  background-size: 100% 100%;
  animation: fadeInLeft;
  animation-duration: 2s;
}
.score-tip {
  position: absolute;
  padding-top: 20px;
  padding-left: 40px;
}
.perfect {
  margin-left: 37%;
}
.good {
  margin-left: 50%;
}
.miss {
  margin-left: 63%;
}
.round {
  width: 100px;
  height: 100px;
  border-radius: 50px;
}
.drum {
  width: 150px;
  height: 150px;
  elevation: higher;
}
.change-back {
  background-color: aqua;
}
.game-sheet {
  margin-top: 20px;
}
.board {
  margin-top: 3%;
  position: relative;
  display: inline-flex;
  height: 250px;
  width: 100%;
  background: rgba(0, 0, 0, 0.2);
}
.action-point {
  margin-top: 75px;
  position: absolute;
  background-image: url("../../static/img/UI/JudgePoint.png");
  background-size: 100% 100%;
}
.button-press {
  margin-top: -50px;
  margin-left: -35px;
  width: 200px;
  height: 200px;
  position: fixed;
  background-image: url("../../static/img/UI/ButtonPress.png");
  background-size: 100% 100%;
}
.judge-button {
  margin-top: -35px;
  margin-left: -18px;
  width: 160px;
  height: 160px;
  position: fixed;
  background-image: url("../../static/img/UI/JudgeButton.png");
  background-size: 100% 100%;
  animation: rotateIn;
  animation-duration: 2s;
}
.cloud {
  position: fixed;
  height: 100px;
  width: 35%;
}
.lcloud {
  margin-top: 150px;
  background-image: url("../../static/img/UI/LeftCloud.png");
  background-size: 100% 100%;
  animation: fadeInLeft;
  animation-duration: 2s;
}
.rcloud {
  margin-top: 150px;
  margin-left: 65%;
  background-image: url("../../static/img/UI/RightCloud.png");
  background-size: 100% 100%;
  animation: fadeInRight;
  animation-duration: 2s;
}
span {
  color: black;
  font-family: '华文楷体', sans-serif;
}
li {
  list-style-type: none;
}
</style>
